package com.example.testio;

import java.io.IOException;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.widget.ListView;
import android.widget.TextView;


public class MainActivity extends Activity {

	private static final int DIALOG_EXTERNAl = 1;
	private static final String FILE_NAME = "test.txt";
	 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createList();
    }
    
    private void createList() {
    	ListDataManager ldm = new ListDataManager(getExternalFilesDir(null), FILE_NAME, getAssets());
    	TextView error = (TextView) findViewById(R.id.test);
    	
    	if (!ldm.hasCard()) {
    		// We can not read and write the media
    		showDialog(DIALOG_EXTERNAl);
    		MainActivity.this.finish();
    	}
    	
		try {
			if (!ldm.hasFile()) {
				ldm.createFile();
			}
		} catch (IOException e) {
			error.setText("External Storage Error writing "+e.getMessage());
			return;
		}
		
		List<String> values;
		try {
			values = ldm.readFile();
		} catch (IOException e) {
			error.setText("External Storage Error reading "+e.getMessage());
			return;
		}
		ListView mainListView = (ListView) findViewById(R.id.mainListView);
		mainListView.setAdapter(new CustomArrayAdapter(this, values));
    }

    @Override
    protected Dialog onCreateDialog(int id) {
      switch (id) {
	      case DIALOG_EXTERNAl:
	        // Create out AlterDialog
	        Builder builder = new AlertDialog.Builder(this);
	        builder.setMessage("You need to set up SD card and click Continue");
	        builder.setCancelable(true);
	        builder.setPositiveButton("Ok", null);
	        AlertDialog dialog = builder.create();
	        dialog.show();
      }
      return super.onCreateDialog(id);
    }
}
